package v2

import (
	"encoding/json"
	"fmt"
	"gomicrov4-sharemod/gateway-api/controllers"
	"gomicrov4-sharemod/gateway-api/utils"
	"time"

	"github.com/gin-gonic/gin"
	"github.com/go-redsync/redsync/v4"
)

type IndexController struct {
	controllers.BaseController
}

func (control IndexController) Index(ctx *gin.Context) {
	// utils.ZLogger.Error(fmt.Sprintf("index error :%s", 59))
	// utils.ZLogger.Error(fmt.Sprintf("safwgvsdvasfasdfddaf"))
	control.BaseSuccess(ctx, control.WithMessage("欢迎使用三叉戟gomicro sharemod 接口 v2"))
}

/**
 * 后端首页
 *
 * @author huwl
 * @date 2025/08/02 14:19:11
 */
func (control IndexController) Backend(ctx *gin.Context) {
	control.BaseSuccess(ctx, control.WithMessage("欢迎使用三叉戟管理接口 v2"))
}

// 测试请求参数
func (control IndexController) TestRequestParams(ctx *gin.Context) {
	params := ctx.PostFormArray("params")
	fmt.Println("params ===", params)
	values := []map[string]interface{}{}
	for _, param := range params {
		value := map[string]interface{}{}
		json.Unmarshal([]byte(param), &value)
		values = append(values, value)
		fmt.Println("value =", value)
	}

	control.BaseSuccess(ctx, control.WithData(values))
}

func (control IndexController) Demo(ctx *gin.Context) {
	searchParams := map[string]interface{}{
		"color": []string{"黑色", "白色", "裸色"},
		"size":  []int64{35, 36, 37},
	}
	b, _ := json.Marshal(searchParams)
	fmt.Println("demo =============== ", string(b))
	control.BaseSuccess(ctx, control.WithData("demo"))
}

func (control IndexController) HttpRequestDemo(ctx *gin.Context) {
	httpMode := ctx.DefaultQuery("http_mode", "get")

	var result map[string]interface{}
	var err error
	if httpMode == "get" {
		result, err = utils.HttpGet("https://api.weixin.qq.com/sns/jscode2session?", map[string]string{
			"appid":      "wxaf1fcde0e826762c",
			"secret":     "09074ca02a7b12d135072b197710d7a0",
			"js_code":    "0f1DA80w3Pt0813JYm1w3BCqc10DA80X",
			"grant_type": "authorization_code",
		})
	} else if httpMode == "post" {
		result, err = utils.HttpPostForm("http://47.100.54.182:7082/api/v1/account/login", map[string]string{
			"username": "huwl",
			"password": "111111",
		})
	}

	if err != nil {
		control.BaseError(ctx, control.WithMessage(err.Error()))
		return
	}

	fmt.Println("result =", result)
	fmt.Println("code =", result["code"])
	data, ok := result["data"]
	if ok {
		control.BaseSuccess(ctx, control.WithData(data))
	} else {
		control.BaseSuccess(ctx, control.WithData(result))
	}
}

func (control IndexController) DemoSendEmail(ctx *gin.Context) {
	toEmail := ctx.DefaultQuery("to_email", "923445472@qq.com")
	subject := ctx.DefaultQuery("subject", "找回密码")

	bodyHtml := `<html>
					<body>
						<p>您的验证码为 345123 ，该验证码5分钟内有效，请勿泄露于他人。</p>
					</body>
				</html>
				`

	err := utils.SendEmail(toEmail, subject, bodyHtml, "html")
	if err != nil {
		control.BaseError(ctx, control.WithMessage(err.Error()))
		return
	}
	control.BaseSuccess(ctx, control.WithData("发送邮件成功"))
}

func (control IndexController) DemoSendSms(ctx *gin.Context) {
	mobile := ctx.DefaultQuery("mobile", "17830244248")

	err := utils.SendSms(mobile, "verificationCodeTemplate", map[string]interface{}{"code": 835019})
	if err != nil {
		control.BaseError(ctx, control.WithMessage(err.Error()))
		return
	}

	control.BaseSuccess(ctx, control.WithData("发送短信成功"))
}

func (control IndexController) RedisLockDemo(ctx *gin.Context) {
	ri, err := utils.NewRedisInstance()
	if err != nil {
		control.BaseError(ctx, control.WithMessage(err.Error()))
		return
	}
	mutex := ri.RsPool.NewMutex("xxxx", redsync.WithExpiry(time.Duration(30)*time.Second))

	err = mutex.Lock()
	if err != nil {
		fmt.Println("err =", err)
	}

	fmt.Println("Get Lock!")

	time.Sleep(time.Second * 1)

	fmt.Println("Start Lock...")
	err = mutex.Lock()
	if err != nil {
		fmt.Printf("lock err:%s\n", err.Error())
		return
	}
	fmt.Println("Get Lock!")

	time.Sleep(time.Second * 30)

	fmt.Println("Unlock!")
	ok, err := mutex.Unlock()
	if !ok {
		fmt.Printf("mutex err:%s\n", err.Error())
		panic("Unlock Failed!")
	}
	if err != nil {
		panic(err)
	}
	fmt.Println("Release Lock!")
	control.BaseSuccess(ctx, control.WithData("redis 分布式锁测试"))
}

// redis 哨兵集群测试
func (control IndexController) RedisSentinelDemo1(ctx *gin.Context) {
	goods := []interface{}{}
	for i := 0; i < 100; i++ {
		goods = append(goods, i)
	}
	ri, err := utils.NewRedisInstance()
	if err != nil {
		control.BaseError(ctx, control.WithMessage(err.Error()))
		return
	}
	err = ri.RedisRpush("goods", goods)
	if err != nil {
		control.BaseError(ctx, control.WithMessage(err.Error()))
		return
	}

	control.BaseSuccess(ctx, control.WithMessage("redis 哨兵集群测试"))
}

// redis 哨兵集群测试
func (control IndexController) RedisSentinelDemo(ctx *gin.Context) {
	ri, err := utils.NewRedisInstance()
	if err != nil {
		control.BaseError(ctx, control.WithMessage(err.Error()))
		return
	}
	good, err := ri.RedisLpop("goods")
	if err != nil {
		control.BaseError(ctx, control.WithMessage(err.Error()))
		return
	}

	fmt.Println("出列表 =========>", good)

	control.BaseSuccess(ctx, control.WithData(good), control.WithMessage("redis 哨兵集群测试"))
}

// redis 分片集群测试
func (control IndexController) RedisClusterDemo(ctx *gin.Context) {
	// 分片集群set操作
	ri, err := utils.NewRedisInstance()
	if err != nil {
		control.BaseError(ctx, control.WithMessage(err.Error()))
		return
	}
	err = ri.RedisClusterClient.Set(ctx, "age", 10, time.Second*900).Err()
	if err != nil {
		control.BaseError(ctx, control.WithMessage(err.Error()))
		return
	}

	// 分片集群get操作
	age, err := ri.RedisClusterClient.Get(ctx, "age").Result()
	if err != nil {
		control.BaseError(ctx, control.WithMessage(err.Error()))
		return
	}

	fmt.Println("age =", age)

	// err := utils.RedisSet("username", "rabbit", time.Second*90)
	// if err != nil {
	// 	control.BaseError(ctx, control.WithMessage(err.Error()))
	// 	return
	// }

	// result, err := utils.RedisGet("username")
	// fmt.Println("result =", result)
	// if err != nil {
	// 	control.BaseError(ctx, control.WithMessage(err.Error()))
	// 	return
	// }

	// fmt.Println("result =", result)

	control.BaseSuccess(ctx, control.WithData("redis 分片集群测试"))
}
